package com.tool_stdy.thread;

/**
 * Created by yan_li on 2017/11/16.
 */
public class DeadLockTest implements Runnable {

    public static Object o1 = new Object();
    public static Object o2 = new Object();
    private boolean flag = false;

    public DeadLockTest(boolean flag) {
        this.flag = flag;
    }

    public static void main(String[] args) {
        try {
            DeadLockTest d1 = new DeadLockTest(true);
            DeadLockTest d2 = new DeadLockTest(false);

            Thread t1 = new Thread(d1, "Thread 1");
            Thread t2 = new Thread(d2, "Thread 2");
            t1.start();
            t2.start();

            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        if (flag) {
            synchronized (o1) {
                System.out.println(Thread.currentThread().getName() + " o1获取锁");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " 准备获取02锁,等待.....");
                synchronized (o2) {
                    System.out.println(Thread.currentThread().getName() + " o2获取锁");
                }
            }
        } else {
            synchronized (o2) {
                System.out.println(Thread.currentThread().getName() + " o2获取锁");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " 准备获取01锁,等待.....");
                synchronized (o1) {
                    System.out.println(Thread.currentThread().getName() + " o1获取锁");
                }
            }
        }
    }
}
